package com.longan.common.config.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.longan.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

@Component
public class CommonMetaObjectHandler implements MetaObjectHandler {

    private final String updateTime = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        setInsertFieldValByName("createUserId", metaObject.hasSetter("deptId") && Objects.nonNull(metaObject.getValue("deptId")) ? null : SecurityUtils.getDeptId().toString(), metaObject);
        setInsertFieldValByName("createUserId", metaObject.hasSetter("createUserId") && Objects.nonNull(metaObject.getValue("createUserId")) ? null : SecurityUtils.getUserId().toString(), metaObject);
        setInsertFieldValByName("createTime", metaObject.hasSetter("createTime") && Objects.nonNull(metaObject.getValue("createTime")) ? null : LocalDateTime.now(), metaObject);
        setInsertFieldValByName(updateTime, metaObject.hasSetter(updateTime) && Objects.nonNull(metaObject.getValue(updateTime)) ? null : LocalDateTime.now(), metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setUpdateFieldValByName(updateTime, LocalDateTime.now(), metaObject);
        setUpdateFieldValByName("updateUserId", SecurityUtils.getUserId(), metaObject);
    }

}
